package com.jielin.handling.exception;

import com.jielin.handling.bean.AppResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

@ControllerAdvice
public class MyExceptionAdvice {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AppResult defaultException(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        // 全局统一拦截了参数校验异常 MethodArgumentNotValidException
        if (e instanceof MethodArgumentNotValidException) {
            // 拿到参数校验具体异常信息提示
            return AppResult.builder().setCode(ResultEnum.FAIL.getCode())
                    .setMsg(((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof ConstraintViolationException) {
            return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg(e.getMessage());
        }
        return AppResult.builder().setCode(ResultEnum.EXCEPTION.getCode()).setMsg(ResultEnum.EXCEPTION.getMsg());
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public AppResult myException(HttpServletRequest request, MyException e) {
        e.printStackTrace();
        int code = e.getCode();
        String message = e.getMessage();
        if (e.getCode() == 0) {
            code = ResultEnum.EXCEPTION.getCode();
        }
        if (e.getMessage() == null) {
            message = ResultEnum.EXCEPTION.getMsg();
        }
        return AppResult.builder().setCode(code).setMsg(message);

    }
}
